package com.wust.footprint;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wust.R;
import com.wust.http.FormFile;
import com.wust.http.HttpUtil;
import com.wust.http.SocketHttpRequester;
import com.wust.user.User;
import com.wust.user.UserDao;
import com.wust.util.ConstDefine;

public class RegisterActivity extends Activity{
	private EditText usertext;
	private EditText passtext;
	private EditText nicktext;
	private Button regbtn;
	private ImageButton logbtn;
	private String iconPath;
	private String tempPath;
	private ImageButton iv;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		
		usertext=(EditText)findViewById(R.id.regist_edit_account);
		passtext=(EditText)findViewById(R.id.regist_edit_pwd);
		nicktext=(EditText)findViewById(R.id.regist_edit_nickname);
		regbtn=(Button)findViewById(R.id.regist_sure);
		iv=(ImageButton)findViewById(R.id.headimg_set);
		logbtn=(ImageButton)findViewById(R.id.regist_title_back);
		regbtn.setOnClickListener(new RegisterListener());
		logbtn.setOnClickListener(new LoginListener());
		init();
	}
	 @Override
		protected Dialog onCreateDialog(int id) {
	    	System.out.println("dialog");
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage("加载中...请稍候");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		}
	class RegisterListener implements OnClickListener
	{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			
			
			
           	if(usertext.getText().toString().equals(""))
			{
				Toast.makeText(RegisterActivity.this, "用户名为空", Toast.LENGTH_SHORT).show();
			}
			else
			{
				showDialog(0);
				new Thread()
				{
					public void run()
					{
						User user=new User();
						user.setUser_name(usertext.getText().toString());
						user.setUser_pass(passtext.getText().toString());
						user.setUser_nickname(nicktext.getText().toString());
						user.setUser_icon(iconPath);
						String iconName=iconPath.substring(iconPath.lastIndexOf("/")+1, iconPath.length());
						Map<String, String> params = new HashMap<String, String>();
			            params.put("user_nickname", nicktext.getText().toString());
			            params.put("user_pass", passtext.getText().toString());
			            params.put("user_name", usertext.getText().toString());
			           
				 File file=new File(iconPath);
				 String result = null;
		          //  System.out.println("file:"+file.getAbsolutePath());
					 FormFile formfile = new FormFile(iconName,file , "image", "application/octet-stream");
					 try {
						result=SocketHttpRequester.post(com.wust.util.ConstDefine.URL+"registeraction", params, formfile);
						JSONObject json=new JSONObject(result);
						System.out.println("result1:"+result);
						if(json.getString(ConstDefine.RegisterUtil.REGISTER_MESSAGE).equals(ConstDefine.RegisterUtil.REGISTER_SUCCESS))
						{
							UserDao userDao=new UserDao(RegisterActivity.this);
							userDao.insertUser(user);
							Intent intent=new Intent(RegisterActivity.this,PicCutDemoActivity.class);
							intent.putExtra("user_name", user.getUser_name());
							startActivity(intent);
							finish();
						}
						else
						{
							Toast.makeText(RegisterActivity.this, "用户名已存在，注册失败", Toast.LENGTH_SHORT).show();
						}
					 
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					}
				}.start();
			
			
		}
		}
	}
	private void init() {
		
		tempPath=Environment.getExternalStorageDirectory()
				+ "/daying/"+"temp.jpg";
		 File file=new File(Environment.getExternalStorageDirectory()
					+ "/daying/");
		 if(!file.isDirectory())
		 {
			 System.out.println("create dir");
			 file.mkdir();
		 }
		iv.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//System.out.println("--------------------");

				 iconPath=Environment.getExternalStorageDirectory()
							+ "/daying/"+usertext.getText().toString()+".jpg";
				ShowPickDialog();
			}
		});
	}
	

	/**
	 * 选择提示对话框
	 */
	private void ShowPickDialog() {
		new AlertDialog.Builder(this)
				.setTitle("设置头像...")
				.setNegativeButton("相册", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						/**
						 * 刚开始，我自己也不知道ACTION_PICK是干嘛的，后来直接看Intent源码，
						 * 可以发现里面很多东西，Intent是个很强大的东西，大家一定仔细阅读下
						 */
						Intent intent = new Intent(Intent.ACTION_PICK, null);
						
						
						intent.setDataAndType(
								MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
								"image/*");
						startActivityForResult(intent, 1);

					}
				})
				.setPositiveButton("拍照", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
						
						Intent intent = new Intent(
								MediaStore.ACTION_IMAGE_CAPTURE);
						//下面这句指定调用相机拍照后的照片存储的路径
						intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
								.fromFile(new File(tempPath)));
						startActivityForResult(intent, 2);
					}
				}).show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		// 如果是直接从相册获取
		case 1:
			startPhotoZoom(data.getData());
			break;
		// 如果是调用相机拍照时
		case 2:
			File temp = new File(iconPath);
			
			startPhotoZoom(Uri.fromFile(temp));
			break;
		// 取得裁剪后的图片
		case 3:
			/**
			 * 非空判断大家一定要验证，如果不验证的话，
			 * 在剪裁之后如果发现不满意，要重新裁剪，丢弃
			 * 当前功能时，会报NullException，小马只
			 * 在这个地方加下，大家可以根据不同情况在合适的
			 * 地方做判断处理类似情况
			 * 
			 */
			if(data != null){
				setPicToView(data);
			}
			break;
		default:
			break;

		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	/**
	 * 裁剪图片方法实现
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {
		/*
		 * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
		 * yourself_sdk_path/docs/reference/android/content/Intent.html
		 * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能,
		 * 是直接调本地库的，小马不懂C C++  这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么
		 * 制做的了...吼吼
		 */
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		//下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 48);
		intent.putExtra("outputY", 48);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}
	
	/**
	 * 保存裁剪之后的图片数据
	 * @param picdata
	 */
	private void setPicToView(Intent picdata) {
		Bundle extras = picdata.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			Drawable drawable = new BitmapDrawable(photo);
			
			/**
			 * 下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上
			 * 传到服务器，QQ头像上传采用的方法跟这个类似
			 */
			
			/*ByteArrayOutputStream stream = new ByteArrayOutputStream();
			photo.compress(Bitmap.CompressFormat.JPEG, 60, stream);
			byte[] b = stream.toByteArray();
			// 将图片流以字符串形式存储下来
			
			tp = new String(Base64Coder.encodeLines(b));
			这个地方大家可以写下给服务器上传图片的实现，直接把tp直接上传就可以了，
			服务器处理的方法是服务器那边的事了，吼吼
			
			如果下载到的服务器的数据还是以Base64Coder的形式的话，可以用以下方式转换
			为我们可以用的图片类型就OK啦...吼吼
			Bitmap dBitmap = BitmapFactory.decodeFile(tp);
			Drawable drawable = new BitmapDrawable(dBitmap);
			*/
			try
			{
				File file=new File(iconPath);
				file.createNewFile();
				FileOutputStream fout=new FileOutputStream(file);
				photo.compress(Bitmap.CompressFormat.JPEG, 100, fout);
				fout.flush();
				fout.close();
				File temp=new File(tempPath);
				if(temp!=null)
					temp.delete();
			}catch(Exception e)
			{
				e.printStackTrace();
			}
			iv.setBackgroundDrawable(drawable);
		}
	}

	class LoginListener implements  OnClickListener
	{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			Intent intent=new Intent(RegisterActivity.this,LoginActivity.class);
			startActivity(intent);
			finish();
		}
		
	}
}
